from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.admin.schemas.tenant import TenantCreate, TenantUpdate,TenantQuery
from app.models.tenant import Tenant


async def get_tenant(db: AsyncSession, tenant_id: str) -> Tenant:
    """
    根据租户ID获取租户
    """
    result = await db.execute(select(Tenant).where(Tenant.id == tenant_id))
    return result.scalar_one_or_none()


async def get_tenant_by_code(db: AsyncSession, code: str) -> Tenant:
    """
    根据租户编码获取租户
    """
    result = await db.execute(select(Tenant).where(Tenant.code == code))
    return result.scalar_one_or_none()


async def get_tenants(db: AsyncSession, query: TenantQuery):
    """
    获取租户列表，支持按条件筛选
    """
    stmt = select(Tenant)

    # 根据条件筛选
    if query.code:
        stmt = stmt.where(Tenant.code.like(f"%{query.code}%"))
    if query.name:
        stmt = stmt.where(Tenant.name.like(f"%{query.name}%"))
    if query.domain:
        stmt = stmt.where(Tenant.domain.like(f"%{query.domain}%"))
    if query.is_active is not None:
        stmt = stmt.where(Tenant.is_active == query.is_active)

    # 分页
    stmt = stmt.offset(query.skip).limit(query.limit)
    result = await db.execute(stmt)
    return result.scalars().all()


async def create_tenant(db: AsyncSession, tenant: TenantCreate) -> Tenant:
    """
    创建新租户
    """
    db_tenant = Tenant(
        id=tenant.id,
        name=tenant.name,
        code=tenant.code,
        domain=tenant.domain,
        max_users=tenant.max_users,
        expire_at=tenant.expire_at
    )
    db.add(db_tenant)
    await db.commit()
    await db.refresh(db_tenant)
    return db_tenant


async def update_tenant(db: AsyncSession, tenant_id: str, tenant_update: TenantUpdate) -> Tenant:
    """
    更新租户信息
    """
    db_tenant = await get_tenant(db, tenant_id)
    if not db_tenant:
        return None

    update_data = tenant_update.model_dump(exclude_unset=True)

    for key, value in update_data.items():
        setattr(db_tenant, key, value)

    await db.commit()
    await db.refresh(db_tenant)
    return db_tenant


async def delete_tenant(db: AsyncSession, tenant_id: str) -> bool:
    """
    删除租户
    """
    db_tenant = await get_tenant(db, tenant_id)
    if not db_tenant:
        return False

    await db.delete(db_tenant)
    await db.commit()
    return True
